package com.dhms.uikit.deviceCategory

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.dhms.uikit.databinding.ItemChipCategoryBinding
import com.dhms.uikit.databinding.ItemDeviceSubCategoryBinding


class DeviceSubCategoryListAdapter(
    private val onItemClick: ((item: DeviceItem) -> Unit) = {}
) :
    ListAdapter<DeviceSubCategoryItem, DeviceSubCategoryListAdapter.DeviceSubCategoryListViewHolder>(
        DiffCallback
    ) {

    var singleSelection: Boolean = false

    class DeviceSubCategoryListViewHolder(var binding: ItemDeviceSubCategoryBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: DeviceSubCategoryItem) {
            binding.item = item
            binding.executePendingBindings()
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<DeviceSubCategoryItem>() {
        override fun areItemsTheSame(
            oldItem: DeviceSubCategoryItem,
            newItem: DeviceSubCategoryItem
        ): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(
            oldItem: DeviceSubCategoryItem,
            newItem: DeviceSubCategoryItem
        ): Boolean {
            return oldItem == newItem
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): DeviceSubCategoryListViewHolder {
        return DeviceSubCategoryListViewHolder(
            ItemDeviceSubCategoryBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: DeviceSubCategoryListViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item)
        val group = holder.binding.chipGroup
        group.isSingleSelection = singleSelection
        val textView = holder.binding.textId
        val textParams = textView.layoutParams

        if (item.ct_name == null) {
            textParams.height = 0
            group.setPadding(0, 0, 0, dip2px(group.context, 10f))
        } else {
            textParams.height = dip2px(group.context, 32f)
            group.setPadding(0, dip2px(group.context, 10f), 0, dip2px(group.context, 10f))
        }
        holder.binding.textId.layoutParams = textParams

        group.removeAllViews()
        item.items?.forEach { deviceItem ->
            val chip = ItemChipCategoryBinding.inflate(LayoutInflater.from(group.context))
            chip.chipItem.id = deviceItem.de_id.hashCode()
            chip.chipItem.isChecked = deviceItem.checkable
            chip.chipItem.text = deviceItem.de_name
            chip.chipItem.setOnClickListener {
                deviceItem.checkable = !deviceItem.checkable
                onItemClick(deviceItem)
            }
            group.addView(chip.root)
        }

    }
}